import 'package:flutter/services.dart';

class AudioStreamManager {
  static const MethodChannel _methodChannel = MethodChannel('com.smarttranslator.audio_control_channel');
  static const EventChannel _eventChannel = EventChannel('com.smarttranslator.audio_stream_channel');

  static const MethodChannel _methodChannel_MAIN = MethodChannel('com.xinyi.smart_translator/channel');

  Stream<dynamic>? _audioStream;

  /*// 开始录音,页面初始化使用.
  Future<void> initService() async {
    try {
      await _methodChannel_MAIN.invokeMethod('startService');
    } on PlatformException catch (e) {
      throw Exception("Failed to start recording: ${e.message}");
    }
  }

  // 开始录音,用户明确停止录音的时候调用.
  Future<void> stopService() async {
    try {
      await _methodChannel_MAIN.invokeMethod('stopService');
    } on PlatformException catch (e) {
      throw Exception("Failed to start recording: ${e.message}");
    }
  }*/

  Future<void> checkerPermission() async {
    try {
      await _methodChannel_MAIN.invokeMethod('checkOverlayPermission');
    } on PlatformException catch (e) {
      throw Exception("Failed to start recording: ${e.message}");
    }
  }

  // 开始录音
  Future<void> startRecording() async {
    try {
      await _methodChannel_MAIN.invokeMethod('startRecording');
    } on PlatformException catch (e) {
      throw Exception("Failed to start recording: ${e.message}");
    }
  }

  // 停止录音
  Future<void> stopRecording() async {
    try {
      await _methodChannel_MAIN.invokeMethod('stopRecording');
    } on PlatformException catch (e) {
      throw Exception("Failed to stop recording: ${e.message}");
    }
  }


  Future<void> startMainActivity() async {
    try {
      await _methodChannel_MAIN.invokeMethod('startMainActivity');
    } on PlatformException catch (e) {
      throw Exception("Failed to stop recording: ${e.message}");
    }
  }


  // 获取录音状态
  Future<bool> isRecording() async {
    try {
      final result = await _methodChannel.invokeMethod('isRecording');
      return result as bool;
    } on PlatformException {
      return false;
    }
  }



  // 获取音频流
  Stream<dynamic> get audioStream {
    _audioStream = _eventChannel
        .receiveBroadcastStream()
        //.map((data) => (data as Map).cast<dynamic>())
        .handleError((error) {
      print("Audio stream error: $error");
    });
    return _audioStream!;
  }
}